﻿package com.tomvian.maths.areas
{
	import com.tomvian.maths.Vector2D;
	
	/**
	 * CircleSectorArea
	 * @author Thomas Vian
	 */
	public class CircleSectorArea extends Area
	{
		//--------------------------------------------------------------------------
		//
		//  Properties
		//
		//--------------------------------------------------------------------------
		
		private var _center:Vector2D;
		private var _radius:Number;
		private var _radiusSqr:Number;
		
		private var _angleMin:Number;
		private var _angleMax:Number;
		private var _angleLeast:Number;
		private var _angleSpan:Number;
		
		private static const twoPi:Number = Math.PI * 2.0;
		
		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		
		public function CircleSectorArea(center:Vector2D, radius:Number, angleMin:Number, angleMax:Number)
		{
			_center = center;
			_radius = radius;
			_radiusSqr = radius * radius;
			
			while (angleMax < 0) 		angleMax += twoPi;
			while (angleMax > twoPi) 	angleMax -= twoPi;
			_angleMax = angleMax;
			
			_angleLeast = _angleMax - twoPi;
			
			while (angleMin < _angleLeast) 	angleMin += twoPi;
			while (angleMin > _angleMax)	angleMin -= twoPi;
			_angleMin = angleMin;
			
			_angleSpan = _angleMax - _angleMin;
			
			area = _radiusSqr * _angleSpan * 0.5;
		}
		
		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------
		
		override public function contains(vector:Vector2D):Boolean 
		{ 
			var diff:Vector2D = vector.subtract(_center);
			
			if(diff.lengthSqr > this.radiusSqr) return false;
			
			var ang:Number = diff.angle;
			while (ang < _angleLeast) 	ang += twoPi;
			while (ang > _angleMax)		ang -= twoPi;
			
			return ang >= this.angleMin;
		}
		
		override public function random():Vector2D 
		{ 
			var rand:Number = Math.random();
			return Vector2D.newFromAngle(Math.random() * _angleSpan + _angleMin, (1 - rand*rand) * _radius).addMod(_center);
		}
	}
}